package com.fansl.allround.open.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.fansl.allround.common.core.constant.enums.EmailMessageTypeEnum;
import com.fansl.allround.common.core.exception.CheckedException;
import com.fansl.allround.common.core.validator.EmailValidator;
import com.fansl.allround.open.api.entity.email.SendMailMessage;
import com.fansl.allround.open.api.entity.email.SendMailMessagePO;
import com.fansl.allround.open.api.vo.EmailCodeVO;
import com.fansl.allround.open.helper.mail.EmailMessageTemplateContext;
import com.fansl.allround.open.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author fansl
 * @Description: 邮箱
 * @date 2019/10/10 12:36
 */
@Slf4j
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private MailService mailService;

    /**
     * 发送验证信息
     * @param receiver
     * @param emailMessageType
     * @return
     */
    @PostMapping("/code")
    public EmailCodeVO sendEmailCode(String receiver,
                                     EmailMessageTypeEnum emailMessageType){
        ComplexResult result = FluentValidator.checkAll()
                .on(receiver,new EmailValidator())
                .doValidate()
                .result(ResultCollectors.toComplex());
        if(!result.isSuccess()){
            throw new CheckedException(result.getErrors().get(0).getErrorMsg());
        }
        EmailCodeVO emailCodeVO = new EmailCodeVO();
        SendMailMessagePO po = new SendMailMessagePO();
        po.setReceiver(receiver);
        po.setEmailMessageType(emailMessageType);

        EmailMessageTemplateContext context = new EmailMessageTemplateContext(po);
        try {
            //生成消息
            SendMailMessage sendMailMessage = context.execute();
            //发送邮件
            mailService.sendMimeMail(sendMailMessage);

            emailCodeVO.setCode((String) sendMailMessage.getReturnContent());
            emailCodeVO.setEmailMessageType(emailMessageType);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("邮箱发送验证码错误",e);
        }
        return emailCodeVO;
    }

}
